
from fastapi import FastAPI,APIRouter,Request
from json.decoder import JSONDecodeError
import sys 
sys.path.append('..')
from utils import user as F 
from utils.http_response import HttpResponse 
from utils.db import engine
from datetime import datetime

def get_formated_time():
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

router = APIRouter(prefix="/user",tags=["user"])

@router.post("/get_one")
async def get_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.select_by_col(engine,body)
    return resp

@router.post("/update_one")
async def update_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    print(body["cond"])
    resp.data = F.update_one(engine,body["cond"],body["item"])  
    return resp 

@router.post("/delete_one")
async def delete_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.delete_one(engine,body)  
    return resp 



@router.post("/add_one")
async def add_one(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    resp.data = F.add_one(engine,body)  
    if resp.data:
        resp.message = "add success"
    else:
        resp.message = "add failed"
        resp.code = 500
    return resp 


@router.post("/login")
async def login(req:Request):
    resp = HttpResponse(code=200,message="success",data=[])
    try:
        body = await req.json()
    except Exception as JSONDecodeError:
        resp.message = "json decode error"
        resp.code = 500
        return resp 
    try:
        res = F.select_by_col(engine,body)  
        if len(res) == 0:
            resp.message = "no such user"
            resp.code = 500
            return resp
        else:
            item =res[0]
            print(item)
            item["login_time"] = get_formated_time()
            res = F.update_one(engine,cond=body,item=item)
            if res:
                resp.data = item
            else:
                resp.message = "update failed"
                resp.code = 500
        return resp
    except Exception as e:
        resp.message = str(e)
        resp.code = 500
        return resp